package org.moelab.trafficlight.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.Unpooled;
import io.netty.channel.*;

/**
 * @author xp
 */
public class ChannelForwardingHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(ChannelForwardingHandler.class);

    private final Channel destChannel;

    public ChannelForwardingHandler(Channel destChannel) {
        this.destChannel = destChannel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        writeAndFlushDestination(msg).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        flushAndCloseDestination();
        ctx.fireChannelInactive();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (LOG.isWarnEnabled()) {
            Channel channel = ctx.channel();
            LOG.warn(String.format("channel %s (local) <-> %s (remote) thrown",
                    channel.localAddress(), channel.remoteAddress()
            ), cause);
        }
        flushAndCloseDestination();
    }

    private ChannelFuture writeAndFlushDestination(Object msg) {
        return destChannel.writeAndFlush(msg);
    }

    private void flushAndCloseDestination() {
        NettyHelper.closeAfterFlush(destChannel);
    }
}
